package services

import (
	wms "ez/apps/wms/document"
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"sort"
)

func UpdateItemSku(item *wms.ItemBase) {
	//item.Read()
	//item.Category.Read()
	item.LoadCategory()
	//按排序规则选出 物品属性
	repAttr := wms.NewItemAttributeCrud()
	curdAttrVal := wms.NewAttributeValueCrud()
	attributes, _ := repAttr.FindBy(ss.M{"ItemBaseId": item.Id}, []string{"sort"}, 0, 0)
	skuMap := make(map[string]string)
	for _, attribute := range attributes {
		temMap := make(map[string]string)
		//读取value列表
		values, e := curdAttrVal.FindBy(ss.M{"kId": attribute.AttributeId}, []string{"sort"}, 0, 0)
		ez.PrintError(e)
		if len(skuMap) == 0 {
			for _, value := range values {
				key := value.Code
				temMap[fmt.Sprintf("%s.%d.%s", item.Category.Code, item.Id, key)] = fmt.Sprintf("%s:%s", item.Name, value.Name)
			}
		} else {
			for k, v := range skuMap {
				for _, value := range values {
					temMap[fmt.Sprintf("%s%s", k, value.Code)] = fmt.Sprintf("%s,%s", v, value.Name)
				}
			}
		}
		skuMap = temMap
	}
	rep := wms.NewItemSkuCrud()
	notSortedKeys := make([]string, 0)
	for key, _ := range skuMap {
		notSortedKeys = append(notSortedKeys, key)
	}
	sort.Strings(notSortedKeys)
	for _, code := range notSortedKeys {
		text := skuMap[code]
		find, e := rep.FindOneBy(ss.M{"code": fmt.Sprintf("%s.%d", code, item.Version), "itemBaseId": item.Id}, nil)
		ez.PrintError(e)
		if find.Id != 0 {
			find.Text = text
		} else {
			find = &wms.ItemSku{}
			find.ItemBaseId = item.Id
			find.Version = item.Version
			find.Code = fmt.Sprintf("%s.%d", code, find.Version)
			find.Text = text
			find.UnitId = item.UnitId
			find.UnitBase = 1
			find.UnitExchange = 1
		}
		find.Save()
	}
}
